package com.graduate.emos.wx;

import ch.qos.logback.core.net.SyslogConstants;
import cn.hutool.core.util.StrUtil;
import com.graduate.emos.wx.common.util.SystemConstants;
import com.graduate.emos.wx.db.dao.SysConfigDao;
import com.graduate.emos.wx.db.pojo.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;

import javax.annotation.PostConstruct;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author Feathermoon
 */
@EnableAsync
@SpringBootApplication
@ServletComponentScan        //开启Servlet组件扫描
@Slf4j
public class EmosWxApiApplication {

    @Autowired
    private SysConfigDao dao;

    @Value("${emos.image-folder}")
    private String imageFolder;

    @Autowired
    private SystemConstants constants;

    public static void main(String[] args) {

        SpringApplication.run(EmosWxApiApplication.class, args);
    }
    //初始化方法
    @PostConstruct
    public void init(){
        //查询数据库常量数据
        List<SysConfig> sysConfigs = dao.selectAllParam();
        //将数据封装到常量对象constants中
        sysConfigs.forEach(sysConfig -> {
            //获取param_key字段
            String paramKey = sysConfig.getParamKey();
            //将带下换线的命名法转化为驼峰命名法,以便于匹配constants中设定的变量
            String key = StrUtil.toCamelCase(paramKey);
            //获取param_value字段
            String paramValue = sysConfig.getParamValue();
            try {
                //获取常量封装类的class
                Class<? extends SystemConstants> constantsClass = constants.getClass();
                //获取变量
                Field field = constantsClass.getDeclaredField(key);
                //通过反射赋值
                field.set(constants,paramValue);
            } catch (Exception e) {
                log.error("执行异常",e);
            }
        });
        log.info(constants.toString());
        /*创建图片文件夹*/
        new File(imageFolder).mkdirs();
    }
}
